package com.dsbj.icardservice.utils.strprocess;

import com.dsbj.icardservice.utils.Constants;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;

/**
 * @author cjw 2019-10-11
 */
public class Base64ImageUtil {
	
	
	/**
	 * 下载downloadUrl对应的文件，并对其进行base64编码，使用了java.util.Base64类。
	 * @param
	 * @return 
	 * @author cjw 2019-10-11
	 */
	public static String encodeFileWithBase64(String downloadUrl) throws IOException {
		
		/**
		 * 下载downloadUrl对应的文件，并对其进行base64编码。
		 */
		URL url=new URL(downloadUrl);
		HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
		httpURLConnection.setConnectTimeout(5 * 1000);
		httpURLConnection.setDoInput(true);
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setUseCaches(false);
		httpURLConnection.setRequestMethod("GET");
		httpURLConnection.setRequestProperty("Charsert", "UTF-8");
		httpURLConnection.connect();
		InputStream inStream=httpURLConnection.getInputStream();
		ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
		
		byte[] temp = new byte[1024];
		int count=0;
		while ((count=inStream.read(temp)) != -1) {
			byteArrayOutputStream.write(temp, 0, count);
		}
		inStream.close();
		//对byteArrayOutputStream中的信息进行base64编码，并返回该编码结果。
		byte[] bytes=byteArrayOutputStream.toByteArray();
		String strEncoded= Base64.getEncoder().encodeToString(bytes);
		return strEncoded;
	}
	
	/**
	 * 将base64编码的字符串进行解码，将解码结果存入文件中，并返回该文件路径。
	 * @param
	 * @return
	 * @author cjw 2019-10-11
	 */
	public static String generateFileFromBase64Str(String strEncoded,String filePath) throws IOException {
		byte[] decodedBytes=Base64.getDecoder().decode(strEncoded);
		FileOutputStream fileOutputStream=new FileOutputStream(filePath);
		fileOutputStream.write(decodedBytes);
		fileOutputStream.close();
		return filePath;
	}
	
	/**
	 * 下载downloadUrl对应的文件，对其进行base64编码，形成编码字符串，并返回该字符串，
	 * 该方法使用了java.util.Base64类。
	 * @param downloadUrl
	 * @return
	 */
	public static String getFileStrBase64_fromDownloadUrl(String downloadUrl){
		String strEncoded=null;
		try {
			strEncoded=encodeFileWithBase64(downloadUrl);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return strEncoded;
	}
	
	/**
	 *
	 * @param
	 * @return
	 * @author cjw 2019-10-11
	 */
	public static void main(String[] args) throws Exception {
		
		String idcardnoUrl="";
		
		String strEncoded=encodeFileWithBase64(idcardnoUrl);
		System.out.println("strEncoded=\n"+strEncoded);
		
		generateFileFromBase64Str(strEncoded,"D://newfile.jpg");
	}
	
	
}
